from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from testing.flow import TestFlow
import urllib
from testing import testcases

_tests = {}

def load_tests(test_dict=_tests):
  reload(testcases)
  for name in dir(testcases):
    value = getattr(testcases, name)
    if value is TestFlow:
      continue
    if not callable(value):
      continue
    if isinstance(value, TestFlow) or name.lower().startswith('test') \
        or name.lower().endswith('test'):
      test_dict[name] = value
  
load_tests()

root_url = '/tests/'
run_url = '%srun' % root_url

class RootPage(webapp.RequestHandler):
  def get(self):
    load_tests()
    self.response.out.write('<h2>Tests</h2>')
    for name,func in _tests.items():
      href = run_url + "?" + urllib.urlencode({'name' : name})
      if func.__doc__ and func.__doc__.strip():
        name = func.__doc__
      elif hasattr(func, 'name'):
        name = func.name
      self.response.out.write("<a href=\"%s\">%s</a><br />" % (href, name))
      
class RunPage(webapp.RequestHandler):
  def get(self):
    name = self.request.get('name')
    func = _tests[name]
    if func.__doc__ and func.__doc__.strip():
      name = func.__doc__
    elif hasattr(func, 'name'):
      name = func.name
    self.response.out.write('<p>' + name + '</p>')
    func(self.response.out)

application = webapp.WSGIApplication([
  (root_url, RootPage),
  (run_url, RunPage),
], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
